package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.entity.ApAuthor;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.entity.WmUser;
import com.heima.user.dto.AuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.feign.ArticleClient;
import com.heima.user.feign.MediaClient;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.IApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author dxx
 * @since 2022-09-19
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {


    @Autowired
    private IApUserService userService;

    @Autowired
    private MediaClient mediaClient;

    @Autowired
    private ArticleClient articleClient;

    @Override
    public ResponseResult listByStatus(AuthDto dto) {

        // 判断状态不为空的话,添加状态查询条件
        // 分页查询
        IPage<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> query = new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null) {
            query.eq(ApUserRealname :: getStatus,dto.getStatus());
        }

        // 按照创建时间倒序排列
        query.orderByDesc(ApUserRealname :: getCreatedTime);
        IPage<ApUserRealname> iPage = this.page(page,query);

        ResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),iPage.getRecords());

        return result;
    }


    @Override
    @GlobalTransactional
    public ResponseResult auth(AuthDto dto, int type) {

        // 判断用户审核失败 type = 0
        // 修改认证表状态为2 审核失败,记录驳回原因
        // 根据认证id查询认证表
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (type == 0) {
            apUserRealname.setStatus(2);
            apUserRealname.setReason(dto.getReason());
            this.updateById(apUserRealname);

            return ResponseResult.okResult();
        }else {

            // 查询app注册表
            ApUser apUser = userService.getById(apUserRealname.getUserId());
            // 创建自媒体账号
            WmUser wmUser = createWmUser(apUser);

            if (wmUser != null) {
                ApAuthor author = createAuthor(apUser, wmUser);
                if (author != null) {
                    apUserRealname.setStatus(9);
                    this.updateById(apUserRealname);
                    // 更新用户注册表flag 为 1自媒体人
                    apUser.setFlag(1);
                    userService.updateById(apUser);
                }
            }
            

        }
        return ResponseResult.okResult();
    }

    private ApAuthor createAuthor(ApUser apUser, WmUser wmUser) {
        // 构建作者
        ApAuthor author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setWmUserId(wmUser.getId());
        // 远程调用
        ResponseResult<ApAuthor> responseResult = articleClient.saveApAuthor(author);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor apAuthor = responseResult.getData();
            if (apAuthor != null) {
                // 更新自媒体账号中的作者id
                wmUser.setApAuthorId(apAuthor.getId());
                mediaClient.updateWmUser(wmUser);
            }
            return apAuthor;
        } else {
            throw new RuntimeException("调用文章服务创建作者失败.");
        }
        // return null;
    }

    private WmUser createWmUser(ApUser apUser) {
        // 构建自媒体账号
        WmUser wmUser = new WmUser();
        // 复制信息,从源拷贝到目标  只有字段名称和类型一致才会拷贝
        BeanUtils.copyProperties(apUser, wmUser);
        wmUser.setId(null);
        wmUser.setApUserId(apUser.getId());
        wmUser.setNickname(apUser.getName());
        wmUser.setStatus(9);
        wmUser.setType(0);
        // 远程调用
        ResponseResult<WmUser> responseResult = mediaClient.saveWmUser(wmUser);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            WmUser user = responseResult.getData();
            return user;
        }
        return null;
    }
}
